package com.gj.remote;


import com.gj.config.BootstrapProperties;
import com.gj.toolkit.http.HttpUtil;
import com.gj.web.base.Result;

import java.util.Map;

/**
 * @方法描述：用来访问服务端的http代理类
 */
public class ServerHttpAgent implements HttpAgent {

    //配置信息对象
    private final BootstrapProperties dynamicThreadPoolProperties;

    //服务地址管理器，这个对象中封装着可用的服务端地址列表，当然，服务端地址的列表信息，需要用户提前定义在配置文件中
    private final ServerListManager serverListManager;

    public ServerHttpAgent(BootstrapProperties properties) {
        this.dynamicThreadPoolProperties = properties;
        this.serverListManager = new ServerListManager(dynamicThreadPoolProperties);
    }

    @Override
    public void start() {
    }

    @Override
    public String getTenantId() {
        return dynamicThreadPoolProperties.getNamespace();
    }

    @Override
    public String getEncode() {
        return null;
    }


    @Override
    public Result httpGetSimple(String path) {
        return HttpUtil.get(buildUrl(path), Result.class);
    }

    //下面就是具体的访问服务端的方法了，这里只需要强调一点，那就是访问服务端之前
    @Override
    public Result httpPost(String path, Object body) {
        return HttpUtil.post(buildUrl(path), body, Result.class);
    }

    @Override
    public Result httpPostByDiscovery(String path, Object body) {
        return HttpUtil.post(buildUrl(path), body, Result.class);
    }

    @Override
    public Result httpGetByConfig(String path, Map<String, String> headers, Map<String, String> paramValues, long readTimeoutMs) {
        return HttpUtil.get(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class);
    }

    @Override
    public Result httpPostByConfig(String path, Map<String, String> headers, Map<String, String> paramValues, long readTimeoutMs) {
        return HttpUtil.post(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class);
    }

    @Override
    public Result httpDeleteByConfig(String path, Map<String, String> headers, Map<String, String> paramValues, long readTimeoutMs) {
        return null;
    }

    private String buildUrl(String path) {
        return serverListManager.getCurrentServerAddr() + path;
    }
}
